package com.ohuang.util_a.task;

/**
 * 失败重新运行
 */
public abstract class FairRestartTask extends Task {
    //最大失败次数  小于0一直重新运行,直到成功
    int maxCount = 1;
    int index = 0;

    public FairRestartTask(int maxCount) {
        this.maxCount = maxCount;
    }

    @Override
    public void run(TaskCallBack taskCallBack) {
        if (index < maxCount || maxCount < 0||!isStop()) {
            index++;
            runTask(create(taskCallBack));
        } else {
            taskCallBack.onNext();
        }
    }

    private FairRestartTaskCallBack create(TaskCallBack taskCallBack) {
        return new FairRestartTaskCallBack() {
            boolean isCall = false;

            @Override
            public void onSuccess() {
                if (!isCall) {
                    isCall = true;
                    taskCallBack.onNext();
                }
            }

            @Override
            public void onFair() {
                if (!isCall) {
                    isCall = true;
                    startRun(taskCallBack);
                }
            }
        };
    }

    public abstract void runTask(FairRestartTaskCallBack fairRestartTaskCallBack);

    public interface FairRestartTaskCallBack {

        void onSuccess();

        void onFair();
    }
}
